package cn.edu.cug.cs.gtl.apis.ui.table;


import cn.edu.cug.cs.gtl.api.wrapper.TableWrapper;
import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.protos.Table;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;

public class TablePanel extends JPanel {


    protected JTable  tableComponent = null;

    public TablePanel(LayoutManager layout, boolean isDoubleBuffered) {
        super(layout, isDoubleBuffered);
    }

    public TablePanel(LayoutManager layout) {
        super(layout);
    }

    public TablePanel(boolean isDoubleBuffered) {
        super(isDoubleBuffered);
    }

    public TablePanel() {
        super();
    }

    public JTable getTableComponent() {
        return tableComponent;
    }


    public void initial(Table table){
        if(table==null){
            tableComponent = new JTable();
            setLayout(new BorderLayout());
            add(new JScrollPane(tableComponent),BorderLayout.CENTER);
        }
        else{
            TableWrapper wrapper = new TableWrapper(table);
            Object[][] data= wrapper.getData();
            Object[] columnNames =wrapper.getColumnNames();
            if(data!=null && columnNames!=null)
                tableComponent = new JTable(data,columnNames);
            else
                tableComponent = new JTable();

            setLayout(new BorderLayout());
            add(new JScrollPane(tableComponent),BorderLayout.CENTER);
        }
    }

    public void initial(Object[] columnNames, Object[][] data){

        if(data!=null && columnNames!=null)
            tableComponent = new JTable(data,columnNames);
        else
            tableComponent = new JTable();

        setLayout(new BorderLayout());
        add(new JScrollPane(tableComponent),BorderLayout.CENTER);
    }


    public void reset(Object[] columnNames,Object[][] data){
        tableComponent.removeAll();
        if(data!=null && columnNames!=null){
            tableComponent.setAutoCreateColumnsFromModel(true);
            DefaultTableModel tableModel = new DefaultTableModel(data,columnNames);
            tableComponent.setModel(tableModel);
        }
    }

    public void reset(Table table){
        tableComponent.removeAll();
        if(table == null ) return;
        if(table!=null){
            TableWrapper wrapper = new TableWrapper(table);
            tableComponent.setAutoCreateColumnsFromModel(true);
            DefaultTableModel tableModel = new DefaultTableModel(wrapper.getData(),wrapper.getColumnNames());
            tableComponent.setModel(tableModel);
        }
    }

}
